package controller;

import com.alibaba.fastjson.JSON;

import entity.ClockInRecord;
import entity.Student;
import service.ClockService;
import service.impl.ClockServicelmpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(urlPatterns = "/clockController")
public class ClockController extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        ClockService c = new ClockServicelmpl();
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        Student user = (Student) session.getAttribute("user");
    
        if ("checkIn".equals(op)) {
            String studentId = user.getUser_id();
            Date clockTime = new Date();
            ClockInRecord clockInRecord = new ClockInRecord(studentId, clockTime);
            
            try {
                boolean success = c.saveCheckIn(clockInRecord);
                if(success) {
                    if(clockInRecord.getStatus() == 0) {
                        out.write(JSON.toJSONString("不在规定打卡时间段内"));
                    } else {
                        out.write(JSON.toJSONString("打卡成功"));
                    }
                } else {
                    out.write(JSON.toJSONString("今日已打卡"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                out.write(JSON.toJSONString("系统错误: " + e.getMessage()));
            }
        }
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
       doPost(req,resp);
    }


}
